package com.laity.demo2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: Laity
 * @Project: JavaLaity
 * @Package: com.laity.demo2.Communication02
 * @Date: 2023年11月22日 21:51
 * @Description: JUC版本 生产者和发布者问题
 */

public class Communication02 {

    static Thread t1 = null, t2 = null, t3 = null, t4 = null;

    public static void main(String[] args) {
        DataSource data = new DataSource();
        t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1");

        t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t2");

        t3 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t3");

        t4 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

// 资源类：线程就是一个单独的资源类，没有附属的操作
class DataSource {
    private int number = 0;

    // 使用JUC创建锁
    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                // 等待
                notFull.await();
            }
            // 业务
            number++;
            System.out.println(Thread.currentThread().getName() + "==>" + number);
            // 通知唤醒
            notFull.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0) {
                // 等待
                notFull.await();
            }
            // 业务
            number--;
            System.out.println(Thread.currentThread().getName() + "==>" + number);
            // 通知唤醒
            notFull.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
